// @algorithm @lc id=100346 lang=cpp
// @title er-cha-sou-suo-shu-de-zui-jin-gong-gong-zu-xian-lcof

#include "algm/algm.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q) {
        TreeNode *minTarget = p->val < q->val ? p : q;
        TreeNode *maxTarget = minTarget == p ? q : p;
        if (root == nullptr) {
            return nullptr;
        }
        if (root->val >= minTarget->val && root->val <= maxTarget->val) {
            return root;
        }
        if (root->val > maxTarget->val) {
            return lowestCommonAncestor(root->left, p, q);
        }
        else {
            return lowestCommonAncestor(root->right, p, q);
        }
    }
};